<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol" name="CPaymentRequestApplyForm">
          <a-row>
            <a-col :span="12">
              <a-form-item label="项目" v-bind="validateInfos.projectId" id="CPaymentRequestApplyForm-projectId" name="projectId">
                <a-select
                  :disabled="disabledFlag"
                  placeholder="请选择"
                  style="width: 100%"
                  v-model:value="formData.projectId"
                  :showSearch="true"
                  :options="projectList"
                  optionFilterProp="label"
                  @change="loadSubProjectList"
                ></a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12" >
              <a-form-item label="子项目" v-bind="validateInfos.subProjectId" id="CPaymentRequestApplyForm-subProjectId" name="subProjectId">
                <a-select
                  :disabled="disabledFlag"
                  placeholder="请选择"
                  style="width: 100%"
                  v-model:value="formData.subProjectId"
                  :showSearch="true"
                  :options="subProjectList"
                  optionFilterProp="label"
                  @change="loadContractorList"
                ></a-select>
              </a-form-item>
            </a-col>
						<a-col :span="12">
							<a-form-item label="分包商" v-bind="validateInfos.contractorId" id="CPaymentRequestApplyForm-contractorId" name="contractorId">
                <a-select
                  :disabled="disabledFlag"
                  placeholder="请选择"
                  style="width: 100%"
                  v-model:value="formData.contractorId"
                  :showSearch="true"
                  :options="contractorList"
                  optionFilterProp="label"
                  @change="contractorOnChange"
                ></a-select>
							</a-form-item>
						</a-col>
            <a-col :span="12" v-if="formData.id ==='' ">
              <a-form-item label="分包商银行" v-bind="validateInfos.subProjectId" id="CPaymentRequestApplyForm-bankId" name="bankId">
                 <j-dict-select-tag showSearch="true"     :trigger-change="true"
                                     @change="bankChange"
                                     v-model:value="formData.bankId"
                                     :disabled="disabledFlag"
                                     :dictCode="bankdist"
                                     placeholder="请选择收款银行"  allow-clear />
              </a-form-item>
            </a-col>


						<a-col :span="12">
							<a-form-item label="申请标题" v-bind="validateInfos.applyTitle" id="CPaymentRequestApplyForm-applyTitle" name="applyTitle">
								<a-input v-model:value="formData.applyTitle" :disabled="disabledFlag" placeholder="请输入申请标题"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
            <a-col :span="12">
              <a-form-item label="申请金额" v-bind="validateInfos.applyAmount" id="CPaymentRequestApplyForm-applyAmount" name="applyAmount">
                <a-input-number :disabled="disabledFlag" v-model:value="formData.applyAmount" placeholder="请输入申请金额" style="width: 100%" />
              </a-form-item>
            </a-col>
						<a-col :span="12">
							<a-form-item label="备注" v-bind="validateInfos.applyRemark" id="CPaymentRequestApplyForm-applyRemark" name="applyRemark">
								<a-textarea :disabled="disabledFlag" v-model:value="formData.applyRemark" :rows="4" placeholder="请输入备注" />
							</a-form-item>
						</a-col>
            <a-col :span="12">
              <a-form-item label="发票" v-bind="validateInfos.recordFile" id="CPaymentRequestApplyForm-recordFile" name="recordFile">
                <j-upload v-model:value="formData.recordFile" dragger="true"   :show-upload-list="{ showDownloadIcon: true, showRemoveIcon: true }" ></j-upload>
              </a-form-item>
            </a-col>



            <a-divider >收款银行信息</a-divider >
            <a-col :span="12">
              <a-form-item label="银行名称" v-bind="validateInfos.bankName" id="CPaymentRequestApplyForm-bankName" name="bankName">
                <a-input :disabled="disabledFlag" v-model:value="formData.bankName" placeholder="请输入银行名称"  allow-clear ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="开户行" v-bind="validateInfos.branchName" id="CPaymentRequestApplyForm-branchName" name="branchName">
                <a-input :disabled="disabledFlag" v-model:value="formData.branchName" placeholder="请输入开户行"  allow-clear ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="银行卡号" v-bind="validateInfos.accountNumber" id="CPaymentRequestApplyForm-accountNumber" name="accountNumber">
                <a-input :disabled="disabledFlag" v-model:value="formData.accountNumber" placeholder="请输入银行卡号"  allow-clear ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="开户人名称" v-bind="validateInfos.accountHolderName" id="CPaymentRequestApplyForm-accountHolderName" name="accountHolderName">
                <a-input :disabled="disabledFlag" v-model:value="formData.accountHolderName" placeholder="请输入开户人名称"  allow-clear ></a-input>
              </a-form-item>
            </a-col>


            <a-col :span="24" v-if="formData.id">
              <a-divider >审核</a-divider >
            </a-col>
            <a-col :span="24" v-if="formData.id">
              <a-form-item label="审核" v-bind="validateInfos.status" id="CPaymentRequestApplyForm-status" name="status">
                 <j-dict-select-tag showSearch="true"   type='radio' v-model:value="formData.status" dictCode="Audit" placeholder="请选择"  allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="24" v-if="formData.id">
              <a-form-item label="审核描述" v-bind="validateInfos.reviewDescription" id="CPaymentRequestApplyForm-reviewDescription" name="reviewDescription">
                <a-textarea v-model:value="formData.reviewDescription" :rows="4" placeholder="请输入审核描述" />
              </a-form-item>

              <a-col :span="24" v-if="formData.reviewTime ">
                <a-form-item label="审核人" v-bind="validateInfos.reviewerUserId" id="CPaymentRequestApplyForm-reviewerUserId" name="reviewerUserId">
                   <j-dict-select-tag showSearch="true"   v-model:value="formData.reviewerUserId" dictCode="sys_user,username,id" placeholder="请选择审核人"  allow-clear />
                </a-form-item>
              </a-col>
              <a-col :span="24" v-if="formData.reviewTime">
                <a-form-item label="审核时间" v-bind="validateInfos.reviewTime" id="CPaymentRequestApplyForm-reviewTime" name="reviewTime">
                  <a-date-picker placeholder="请选择审核时间"  v-model:value="formData.reviewTime" showTime value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%"  allow-clear />
                </a-form-item>
              </a-col>


            </a-col>
          </a-row>
          <a-row  v-if="formData.status==='已付款'">

              <a-divider >财务</a-divider >
              <a-col :span="24">
                <a-form-item label="财务人" v-bind="validateInfos.financialUserId" id="CPaymentRequestApplyForm-financialUserId" name="financialUserId">
                   <j-dict-select-tag showSearch="true"   v-model:value="formData.financialUserId" dictCode="sys_user,username,id" placeholder="请选择财务人"  allow-clear />
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <a-form-item label="财务审核时间" v-bind="validateInfos.financialTime" id="CPaymentRequestApplyForm-financialTime" name="financialTime">
                  <a-date-picker placeholder="请选择财务审核时间"  v-model:value="formData.financialTime" showTime value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%"  allow-clear />
                </a-form-item>
              </a-col>



          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import JUpload from '/@/components/Form/src/jeecg/components/JUpload/JUpload.vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import { getValueType } from '/@/utils';
  import { saveOrUpdate,getBankById } from '../CPaymentRequestApply.api';
  import { Form } from 'ant-design-vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import { getContractorList, getProjectList, getSubProjectList } from '@/views/common.api';
  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => ({})},
    formBpm: { type: Boolean, default: true }
  });
  const formRef = ref();
  const useForm = Form.useForm;
  const disabledFlag = ref(false)
  const emit = defineEmits(['register', 'ok']);
  let bankdist = ref("c_bank_info,bank_name,id,contact_id=0")
  const formData = reactive<Record<string, any>>({
    id: '',
    projectId: undefined,
    subProjectId: undefined,
    contractorId: undefined,
    applyTitle: '',   
    applyRemark: '',   
    applyAmount: undefined,
    status: '',   
    reviewerUserId: '',   
    reviewTime: '',   
    reviewDescription: '',   
    submitterUserId: '',   
    submissionTime: '',   
    financialUserId: '',   
    financialTime: '',   
    requestId: '',
    bankName: '',
    branchName: '',
    accountNumber: '',
    accountHolderName: '',
    bankId:'',//虚拟字段
    recordFile: '',
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = reactive({
  });
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });

  // 表单禁用
  const disabled = computed(()=>{
    if(props.formBpm === true){
      if(props.formData.disabled === false){
        return false;
      }else{
        return true;
      }
    }
    return props.formDisabled;
  });

  
  /**
   * 新增
   */
  function add() {
    edit({});

  }

  /**
   * 编辑
   */
  function edit(record) {
    loadProjectList()
    if(record != undefined ){
      if(record.projectId != undefined &&
        record.projectId != null){
        loadSubProjectList(record.projectId);
      }
      if(record.subProjectId != undefined &&
        record.subProjectId != null){
        loadContractorList(record.subProjectId);
      }
    }
    nextTick(() => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if(record.hasOwnProperty(key)){
          tmpData[key] = record[key]
        }
        if(key ==="status"){
          if(record[key] ==="待付款"){
            tmpData[key] = "同意"
          }else if(record[key] ==="已付款"){
            tmpData[key] = "同意"
          }else if(record[key] ==="待付款"){
            tmpData[key] = "同意"
          }else {
            tmpData[key] = record[key]
          }
        }
      })
      //赋值
      Object.assign(formData, tmpData);
      if(record.id){
        disabledFlag.value = true
      }else {
        disabledFlag.value = false
      }
    });


  }

  /**
   * 查询分包商的银行信息
   * @param value
   */
  async function contractorOnChange(value){
    if(value){
      formData.bankId = "";
      bankdist.value = "c_bank_info,bank_name,id,contact_id="+value
      formData.bankName = "";
      formData.branchName = "";
      formData.accountNumber = "";
      formData.accountHolderName = "";
    }
    //查询信息
  }
  async function bankChange(value){
    if(value){
      const param = {'id':value}
      try {
        const result = await getBankById(param)
        if(result){
          formData.bankName = result.bankName
          formData.branchName = result.branchName
          formData.accountNumber = result.accountNumber
          formData.accountHolderName = result.accountHolderName
        }
      }catch (e) {

      }
    }else {
      formData.bankName = "";
      formData.branchName = "";
      formData.accountNumber = "";
      formData.accountHolderName = "";
    }
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    try {
      // 触发表单验证
      await validate();
    } catch ({ errorFields }) {
      if (errorFields) {
        const firstField = errorFields[0];
        if (firstField) {
          formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
        }
      }
      return Promise.reject(errorFields);
    }
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }

  /**
   * 加载 主项目下拉
   */
  const projectList = ref([])
  async function loadProjectList(){
    projectList.value = []
    projectList.value = await getProjectList()
  }
  /**
   * 加载 子主项目 下拉
   */
  const subProjectList = ref([])
  async function loadSubProjectList(projectId){
    formData.subProjectId=undefined
    subProjectList.value = []
    formData. contractorId=undefined
    contractorList.value = []
    contractorOnChange("1234")
    const params = {'projectId':projectId}
    subProjectList.value = await getSubProjectList(params)
  }

  /**
   * 加载 分包商
   */
  const contractorList = ref([])
  async function loadContractorList(subProjectId){
    formData. contractorId=undefined
    contractorList.value = []
    contractorOnChange("1234")
    const params = {'subProjectId':subProjectId}
    contractorList.value = await getContractorList(params)
  }



  defineExpose({
    add,
    edit,
    submitForm,
    disabledFlag,
    contractorOnChange,
    bankdist,
    bankChange,
    loadProjectList,
    loadSubProjectList,
    loadContractorList,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    padding: 14px;
  }
</style>
